package com.boot.jdk8;

import com.boot.model.Shop;

import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;

import static java.util.stream.Collectors.toList;

public class CompletableFutureTester {

    public static void main(String[] args) {
//        Shop shop = new Shop("BestShop");
//        long start = System.currentTimeMillis();
//        Future<Double> future = shop.getPriceAsync("My Favorite");
//        long invocationTime = System.currentTimeMillis() - start;
//        System.out.println("调用接口时间：" + invocationTime + "毫秒");
//
//        doSomethingElse();
//
//        try {
//            double price = future.get();
//        } catch (InterruptedException e) {
//            e.printStackTrace();
//        } catch (ExecutionException e) {
//            e.printStackTrace();
//        }
//
//        long retrievalTime = System.currentTimeMillis() - start;
//        System.out.println("返回价格消耗时间：" + retrievalTime + "毫秒");
        List<Shop> shops = Arrays.asList(new Shop("sunjin.org"),
                new Shop("加瓦匠"),
                new Shop("京东商城"),
                new Shop("天猫商城"));

        long start1 = System.currentTimeMillis();
        System.out.println(findPrice("parallelStream",shops));
        long duration = System.currentTimeMillis() - start1;
        System.out.println("parallelStream 总消耗时间：" + duration + "毫秒");
        List<Shop> shops1 = Arrays.asList(new Shop("sunjin.org"),
                new Shop("加瓦匠"),
                new Shop("京东商城"),
                new Shop("天猫商城"));

        long start2 = System.currentTimeMillis();
        System.out.println(findPrice2("CompletableFuture",shops1));
        long duration2 = System.currentTimeMillis() - start2;
        System.out.println("CompletableFuture 总消耗时间：" + duration2 + "毫秒");


    }

    public static void doSomethingElse(){
        System.out.println("做其他的事情。。。");
    }
    public static List<String> findPrice(String product,List<Shop> shops){
        return shops.parallelStream()
                .map(shop -> String.format("%s 的价格是 %.2f", shop.getName(),shop.getPrice(product)))
                .collect(toList());

    }

    public static List<String> findPrice2(String product,List<Shop> shops){
        List<CompletableFuture<String>> priceFuture = shops.stream()
                .map(shop -> CompletableFuture.supplyAsync( // 使用异步的方式计算每种商品的价格
                        () -> shop.getName() + " 的价格是 " + shop.getPrice(product)))
                .collect(toList());

        return priceFuture.stream()
                .map(CompletableFuture::join) //join 操作等待所有异步操作的结果
                .collect(toList());
    }
}
